using Devil;
using UnityEngine;
using UnityEngine.UI;

namespace GameToolkit
{
    [RequireComponent(typeof(Text))]
    public class FpsCounter : MonoBehaviour
    {

        [Range(0.1f, 2f)]
        public float m_UpdateRate = 0.5f;
        float frames;
        float time;
        protected float fps;
        protected Text mText;

        //public int limitFps = -1;

        protected virtual void Start()
        {
            frames = 0;
            time = 0;
            fps = 0;
            mText = GetComponent<Text>();
            //SetFpsLimit(false);
        }

        //void SetFpsLimit(bool check)
        //{
        //    var limit = Mathf.Max(0, limitFps);
        //    if (!check || limit != limitFpsValue)
        //    {
        //        limitFpsValue = limit;
        //        if (limitFpsValue > 0)
        //        {
        //            QualitySettings.vSyncCount = 0;
        //            Application.targetFrameRate = limitFpsValue;
        //        }
        //        else
        //        {
        //            QualitySettings.vSyncCount = 1;
        //        }
        //    }
        //}

        void CountFps()
        {
            frames++;
            time += Time.unscaledDeltaTime;
            fps = frames / time;
        }

        protected virtual void UpdateContent()
        {
            mText.text = ParallelUtils.Concat(Mathf.Round(fps), "FPS");
        }

        protected virtual void Update()
        {
            CountFps();
            if (time >= m_UpdateRate)
            {
                UpdateContent();
                frames = 0;
                time = 0;
            }
        }

        //int limitFpsValue;

        //private void OnValidate()
        //{
        //    if (Application.isPlaying && limitFpsValue != limitFps)
        //        SetFpsLimit(true);
        //}
    }
}